﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QAxObject>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    modbus = new ModbusRTU(ui->listWidget);

    Init_UIPort();

    time = new QTimer(this);
    connect(time, SIGNAL(timeout()), this, SLOT(NowTime()));
    time->start(200);

    Init_Setini();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *)
{
    QSettings *set = new QSettings("./set.ini", QSettings::IniFormat);

    set->setValue("SerialPort/baud", ui->BaudRateBox->currentIndex());
    set->setValue("SerialPort/databits", ui->DataBitsBox->currentIndex());
    set->setValue("SerialPort/parity", ui->ParityBox->currentIndex());
    set->setValue("SerialPort/stopbits", ui->StopBitsBox->currentIndex());
    set->setValue("SerialPort/responDelayTime", ui->ResponDelayLE->text());
    set->setValue("SerialPort/modbusAddr", ui->addrLe->text());

    delete set;
}

void MainWindow::Init_UIPort()
{
    ui->statusBar->setSizeGripEnabled(false);//去掉状态栏右下角的三角
    QLabel *permanent=new QLabel(this);
    permanent->setText(tr("Towel Roll"));
    permanent->setStyleSheet("color: rgb(157, 157, 157)");
    ui->statusBar->addPermanentWidget(permanent);//显示永久信息

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        //qDebug()<<"Name : "<<info.portName();
        ui->PortBox->addItem(info.portName());
    }
    UIState(false);
}

void MainWindow::Init_Setini()
{
    QSettings *set = new QSettings("./set.ini", QSettings::IniFormat);

    ui->BaudRateBox->setCurrentIndex(set->value("SerialPort/baud", 3).toInt());
    ui->DataBitsBox->setCurrentIndex(set->value("SerialPort/databits", 3).toInt());
    ui->ParityBox->setCurrentIndex(set->value("SerialPort/parity", 0).toInt());
    ui->StopBitsBox->setCurrentIndex(set->value("SerialPort/stopbits", 0).toInt());
    ui->ResponDelayLE->setText(set->value("SerialPort/responDelayTime", 500).toString());
    ui->addrLe->setText(set->value("SerialPort/modbusAddr", 0).toString());
    modbus->ChangeModbusAddr(set->value("SerialPort/modbusAddr", 0).toInt());
//    qDebug()<<set->value("SerialPort/modbusAddr", 0).toString();
    delete set;
}


//true 串口打开 ， false 串口关闭
void MainWindow::UIState(bool state)
{
    if(state)
    {
        ui->tabWidget->setEnabled(true);
    }
    else
    {
        ui->tabWidget->setDisabled(true);
    }
}

void MainWindow::SerialPortClose()
{
    MySerialPort->close();
    delete MySerialPort;
    MySerialPort = nullptr;
    ui->ControlPortCB->setText("打开串口");
    UIState(false);
    portStatus = false;
}

bool MainWindow::SerialPortOpen()
{
    MySerialPort = new QSerialPort();
    MySerialPort->setPortName(ui->PortBox->currentText());

    if(MySerialPort->open(QIODevice::ReadWrite))        //设置为打开的状态
    {
        MySerialPort->setBaudRate(modbus->baudRate(ui->BaudRateBox->currentIndex()));
        MySerialPort->setDataBits(modbus->dataBits(ui->DataBitsBox->currentIndex()));
        MySerialPort->setParity(modbus->parity(ui->ParityBox->currentIndex()));
        MySerialPort->setStopBits(modbus->stopBits(ui->StopBitsBox->currentIndex()));

        modbus->changeResponDelayTime(ui->ResponDelayLE->text().toInt());

        qDebug()<<"BaudRate:"<<MySerialPort->baudRate()<<
                  "DataBits:"<<MySerialPort->dataBits()<<
                  "Parity:"<<MySerialPort->parity()<<
                  "StopBits:"<<MySerialPort->stopBits()<<
                  "ResponDelayTime"<<ui->ResponDelayLE->text()<<endl;

        connect(MySerialPort, &QSerialPort::readyRead, this, &MainWindow::answer);

        ui->ControlPortCB->setText("关闭串口");
        UIState(true);
    }
    else
    {
        QMessageBox::warning(this, tr("警告"), tr("串口打开失败"), QMessageBox::Ok);
        disconnect(MySerialPort, &QSerialPort::readyRead, this, &MainWindow::answer);
        delete MySerialPort;
        MySerialPort = nullptr;
        return false;
    }
    return true;
}

void MainWindow::NowTime()
{
    //nowtime.setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    ui->statusBar->showMessage(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

    if(ui->listWidget->count() >= 50)
        ui->listWidget->clear();
}

void MainWindow::on_ControlPortCB_clicked()
{
    if(!portStatus)
       portStatus = SerialPortOpen();
    else
        SerialPortClose();
}

void MainWindow::answer()
{
    if(MySerialPort == NULL)
        return;

    QTimer::singleShot(ui->ResponDelayLE->text().toInt(), this, [=](){
        if(MySerialPort == NULL)
            return;
        QByteArray ba = MySerialPort->readAll();
        if(ba.isNull() || ba.length() != 8)
            return;
        SerialPort sp;
        QString cmd = sp.ShowHex(ba);
        ui->listWidget->addItem(QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] :")
                                   + cmd);
        ui->listWidget->item(ui->listWidget->count()-1)->setTextColor(Qt::blue);
        ui->listWidget->setCurrentRow(ui->listWidget->count()-1);

        if(!modbus->CheckCRCModbus((uint8_t *)ba.data(), ba.size()))
            return;

        int nums = ba[5];

        ba = modbus->AutoWriteModbus(nums, ba);
        MySerialPort->write(ba);
        cmd = sp.ShowHex(ba);
        ui->listWidget->addItem(QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] :")
                                   + cmd);
        ui->listWidget->item(ui->listWidget->count()-1)->setTextColor(Qt::red);
        ui->listWidget->setCurrentRow(ui->listWidget->count()-1);

        if(MySerialPort == NULL)
            return;
        MySerialPort->readAll();
    });
}


void MainWindow::on_ClearMessagePB_clicked()
{
    ui->listWidget->clear();
}
